package leetcode;

import java.util.List;

/*
    两数相加
 */
public class Demo02 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3,new ListNode(1))));
        ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
        ListNode listNode = addTwoNumbers(l1, l2);
        ListNode temp = listNode;
        while (temp != null) {
            System.out.println(temp.val);
            temp = temp.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = null;
        boolean flag = false;
        ListNode temp1 = l1;
        ListNode temp2 = l2;
        ListNode temp3 = null;
        while (temp1 != null && temp2 != null) {
            if (result == null) {
                result = new ListNode((temp1.val + temp2.val) % 10);
                temp3 = result;
            } else {
                temp3.next = new ListNode(flag ? (temp1.val + temp2.val) % 10 + 1 : (temp1.val + temp2.val) % 10);
                temp3 = temp3.next;
            }
            flag = (temp1.val + temp2.val) >= 10 ? true : false;
            temp1 = temp1.next;
            temp2 = temp2.next;
        }
        //将没有算完的添加到result后面
        if (temp1 != null) {
            temp3.next = temp1;
        }
        if (temp2 != null) {
            temp3.next = temp2;
        }
        return result;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

